declare
fun {BFSAcc T}
   fun {TreeInsert Q T}
      if T\=leaf then {Insert Q T} else Q end   end

   proc {BFSQueue Q1 ?S1 Sn}
      if {IsEmpty Q1} then S1=Sn
      else X Q2 Key Val L R S2 in
         Q2={Delete Q1 X}
         tree(Key Val L R)=X
         S1=Key#Val|S2
         {BFSQueue {TreeInsert {TreeInsert Q2 L} R} S2 Sn}
      end
   end
in
   {BFSQueue {TreeInsert {NewQueue} T} $ nil}
end
